package com.sg.util.XMLTools;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.sg.util.XMLTools.entity.XMLNode;

public class XMLReader {

	/**
	 * 读取文件
	 * @param filePath 文件路径
	 * @return 文件对象
	 */
	private static File readFile(String filePath){
		File file = new File(filePath);
		if (file.exists() && file.length() > 0 ) {
			return file;
		}
		else{
			return null;
		}
	}
	
	/**
	 * 创建节点
	 * @param e dom节点
	 * @return {@link XMLNode} xml节点
	 */
	private static XMLNode createNode(Element e){
		XMLNode node = new XMLNode();
		node.setParent(e.elements().size() > 0);
		
		node.setNodeTag(e.getName());
		
		node.setNodeText(e.getText());
		Map<String, String> attributeMap = new HashMap<String, String>();
		for (Object attrObj : e.attributes()) {
			Attribute attr = (Attribute) attrObj;
			attributeMap.put(attr.getName(), attr.getValue());
		}
		node.setAttributes(attributeMap);
		List<XMLNode> childs = new ArrayList<XMLNode>();
		node.setChilds(childs);
		for (Object childObject : e.elements()) {
			Element child = (Element) childObject;
			childs.add(createNode(child));
		}
		
		return node;
	}
	
	/**
	 * 读取dom
	 * @param filePath 文件路径
	 * @return {@link XMLNode} dom节点
	 * @throws DocumentException 文档解析异常
	 * @throws NullPointerException 空指针异常
	 */
	public static XMLNode readDom(String filePath) throws DocumentException, NullPointerException {
		SAXReader reader = new SAXReader();
		File file = readFile(filePath); 
		if (file == null) {
			return new XMLNode();
		}
		
		Document document = reader.read(file);
		
		Element root = document.getRootElement();
		
		return createNode(root);
	}
	
	/**
	 * 读取dom
	 * @param filePath 文件路径
	 * @param sPath 元素xPath路径
	 * @return {@link XMLNode} dom节点
	 * @throws DocumentException 文档解析异常
	 * @throws NullPointerException 空指针异常
	 */
	public static List<XMLNode> readDom(String filePath, String sPath) throws DocumentException, NullPointerException {
		SAXReader reader = new SAXReader();
		List<XMLNode> nodes = new ArrayList<XMLNode>();
		
		File file = readFile(filePath); 
		if (file == null) {
			return new ArrayList<XMLNode>();
		}
		
		Document document = reader.read(file);
		
		@SuppressWarnings("unchecked")
		List<Element> selectedElement = document.selectNodes(sPath);
		
		for (Element element : selectedElement) {
			nodes.add(createNode(element));
		}
		
		return nodes;
	} 
}
